import Web3 from "web3";
import DonationPlatform from "E:/Vue3/vite-project/build/contracts/DonationPlatform.json"; 

let web3;
let contract;
let selectedAccount;

export const initWeb3 = async () => {
  if (window.ethereum) {
    web3 = new Web3(window.ethereum);
    await window.ethereum.request({ method: "eth_requestAccounts" });
    const networkId = await web3.eth.net.getId();
    const deployedNetwork = DonationPlatform.networks[networkId];  // 使用 ABI 获取部署网络

    contract = new web3.eth.Contract(
      DonationPlatform.abi,  // 合约的 ABI
      deployedNetwork && deployedNetwork.address  // 合约地址
    );

    const accounts = await web3.eth.getAccounts();
    selectedAccount = accounts[0];
  } else {
    alert("请安装 MetaMask");
  }
};

export const donate = async (projectId, amount) => {
  await contract.methods.donate(projectId).send({
    from: selectedAccount,
    value: web3.utils.toWei(amount, "ether"),
  });
};

export const getProjectInfo = async (projectId) => {
  return await contract.methods.projects(projectId).call();
};

export const getCurrentAccount = async () => {
  const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
  return accounts[0];
};
